<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small" v-if="mode === 'list'">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="企业" prop="workCorpId">
                            <el-select v-model="condition.search.workCorpId" placeholder="请选择企业"
                                       style="width:200px;">
                                <el-option
                                    v-for="item in corps"
                                    :key="item.id"
                                    :label="item.corpName"
                                    :value="item.id">
                                    {{ item.corpName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="用户ID" prop="userid">
                            <el-input v-model="condition.search.userid"
                                      placeholder="用户ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="condition.search.name"
                                      placeholder="姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="手机号码" prop="mobile">
                            <el-input v-model="condition.search.mobile"
                                      placeholder="手机号码"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="condition.search.gender"
                                       placeholder="性别">
                                <el-option label="未知"
                                           value="0"></el-option>
                                <el-option label="男性"
                                           value="1"></el-option>
                                <el-option label="女性"
                                           value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="condition.search.status"
                                       placeholder="状态">
                                <el-option label="已激活"
                                           value="1"></el-option>
                                <el-option label="已禁用"
                                           value="2"></el-option>
                                <el-option label="未激活"
                                           value="4"></el-option>
                                <el-option label="退出企业"
                                           value="5"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="sync">同步</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            ref="employeeTable"
            id="employeeTable"
            :data="tableData"
            size="small"
            @selection-change="handleSelectionChange"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column type="selection" width="55" v-if="mode === 'select'"></el-table-column>
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="userid"
                label="用户ID">
            </el-table-column>
            <el-table-column
                prop="name"
                width="80px"
                label="姓名">
            </el-table-column>
            <el-table-column
                prop="mobile"
                width="80px"
                label="手机号码">
            </el-table-column>
            <el-table-column
                prop="gender"
                width="80px"
                :formatter="formatGender"
                label="性别">
            </el-table-column>
            <el-table-column
                prop="status"
                width="80px"
                :formatter="formatStatus"
                label="状态">
            </el-table-column>
            <el-table-column
                prop="welcomeTitle"
                v-if="mode === 'list'"
                label="欢迎语">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                v-if="mode === 'list'"
                prop="syncTime"
                label="同步时间">
            </el-table-column>
            <el-table-column
                v-if="mode === 'list'"
                prop="detail"
                label="详情">
                <template v-slot="scope">
                    <table-popover :length=32 :text=scope.row.detail></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                v-if="mode !== 'select'"
                label="操作"
                fixed="right"
                align="center"
                width="100px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onRefresh(scope.row)" type="text" size="small">刷新</el-button>
                        <el-dropdown>
                            <el-button type="text" size="small">
                                更多
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item>
                                    <el-button @click="configWelcomeMsg(scope.row)" type="text" size="small">
                                        配置欢迎语
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item>
                                    <el-button @click="sendMessage(scope.row)" type="text" size="small">发送消息
                                    </el-button>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item label="用户ID">
                    <el-input v-model="addOrUpdateForm.userid"
                              placeholder="用户ID"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="addOrUpdateForm.name"
                              placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="addOrUpdateForm.mobile"
                              placeholder="手机号码"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="addOrUpdateForm.gender"
                              placeholder="性别"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-input v-model="addOrUpdateForm.status"
                              placeholder="状态"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="OPEN_ID">
                    <el-input v-model="addOrUpdateForm.openUserid"
                              placeholder="OPEN_ID"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="addOrUpdateDialogVisible = false">取 消</el-button>
                <el-button size="small" @click="addOrUpdateConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title=发送消息 width="50%" :visible.sync="sendMessageDialogVisible">
            <el-form :model="sendMessageForm" label-width="120px" size="small">
                <el-form-item label="选择消息类型">
                    <el-radio-group v-model="sendMessageForm.msgType">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-radio label="text">文本消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="image">图片消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="voice">语音消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="video">视频消息</el-radio>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-radio label="file">文件消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="textcard">文本卡片消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="news">图文消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="mpnews">图文消息（新）</el-radio>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-radio label="markdown">markdown消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="miniprogram_notice">小程序通知消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="template_card">模板卡片消息</el-radio>
                            </el-col>
                            <el-col :span="6">
                                <el-radio label="develop">其它消息开发中......</el-radio>
                            </el-col>
                        </el-row>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="请输入文本内容" v-if="sendMessageForm.msgType === 'text'">
                    <el-input type="textarea" v-model="sendMessageForm.textContent"></el-input>
                </el-form-item>
                <el-form-item label="选择图片" v-if="sendMessageForm.msgType === 'image'">
                    <el-button @click="selectMaterialDialogVisible = true" size="mini" type="success">
                        选择图片
                    </el-button>
                    <div v-if="selectedMaterial.id" style="margin-top: 10px">
                        <material-show :info="selectedMaterial"></material-show>
                        <div>{{ selectedMaterial.title }}</div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="sendMessageDialogVisible = false">取 消</el-button>
                <el-button size="small" @click="sendMessageConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择图片" width="70%" :visible.sync="selectMaterialDialogVisible" append-to-body>
            <work-material ref="materialSelect" size="small" @select="onSelectMaterial" mode="select"
                           :work-corp-id="selectedRow.workCorpId"></work-material>
            <div slot="footer" class="dialog-footer"></div>
        </el-dialog>

        <el-dialog title="配置欢迎语" width="50%" :visible.sync="welcomeMsgDialogVisible">
            <work-welcome-msg ref="welcomeMsg" size="small" mode="select" :work-corp-id="selectedRow.workCorpId"
                              :selected="selectedWelcomeMsgs"></work-welcome-msg>
            <div slot="footer" class="dialog-footer">
                <el-button @click="welcomeMsgDialogVisible = false" :size="size">关 闭</el-button>
                <el-button @click="configWelcomeMsgConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addWorkEmployee,
    configWelcomeMsgWorkEmployee,
    deleteWorkEmployee,
    getWorkCorpByPage,
    getWorkEmployeeByPage,
    getWorkWelcomeMsgById,
    refreshWorkEmployee,
    sendMessageToEmployee,
    syncWorkEmployee,
    updateWorkEmployee
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";
import WorkMaterial from "@/component/workwx/WorkMaterial";
import MaterialShow from "@/component/workwx/MaterialShow";
import WorkWelcomeMsg from "@/component/workwx/WorkWelcomeMsg";

export default {
    name: "WorkEmployee",
    components: {WorkMaterial, TablePopover, MaterialShow, WorkWelcomeMsg},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // 公司信息
            corps: [],

            employeeSelected: [],

            sendMessageDialogVisible: false,
            sendMessageForm: {},

            selectMaterialDialogVisible: false,
            selectedMaterial: [],

            // 欢迎语配置
            welcomeMsgDialogVisible: false,
            selectedWelcomeMsgs: [],
            welcomeMsgForm: {},
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mode: {
            type: String,
            default: 'list'
        },
        // 选中的行
        selected: {
            type: Array,
            default: () => []
        },
        workCorpId: String
    },
    watch: {
        selected: function (val, oldVal) {
            this.selected = val;
            this.setChecked();
        },
        workCorpId: function (val, oldVal) {
            this.condition.search.workCorpId = val;
        }
    },
    methods: {
        handleSelectionChange(val) {
            this.employeeSelected = val;
        },
        onSelectMaterial(row) {
            this.selectedMaterial = row;
            this.selectMaterialDialogVisible = false;
            this.sendMessageForm.workMaterialId = row.id;
        },
        sendMessage(row) {
            this.selectedRow = row;
            this.sendMessageForm.userid = row.userid;
            this.sendMessageDialogVisible = true;
        },
        sendMessageConfirm() {
            sendMessageToEmployee(this.sendMessageForm).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '发送成功!'
                    });
                    this.sendMessageDialogVisible = false;
                }
            })
        },
        configWelcomeMsg(row) {
            this.selectedRow = row;
            this.selectedWelcomeMsgs = [];
            if (row.welcomeId) {
                getWorkWelcomeMsgById({id: row.welcomeId}).then(data => {
                    if (data.body) {
                        this.selectedWelcomeMsgs.push(data.body);
                    }
                })
            }
            this.welcomeMsgDialogVisible = true;
            this.welcomeMsgForm.id = row.id;
        },
        configWelcomeMsgConfirm() {
            this.selectedWelcomeMsgs = this.$refs.welcomeMsg.welcomeMsgSelected;
            if (this.selectedWelcomeMsgs.length > 0) {
                if (this.selectedWelcomeMsgs.length > 1) {
                    this.$message({
                        type: 'error',
                        message: '只能配置一条欢迎语'
                    });
                    return;
                }
                this.welcomeMsgForm.welcomeId = this.selectedWelcomeMsgs[0].id;
            } else {
                this.$message({
                    type: 'error',
                    message: '请选择一条欢迎语'
                });
                return;
            }
            configWelcomeMsgWorkEmployee(this.welcomeMsgForm).then(data => {
                if (data.respCode == 1000) {
                    this.welcomeMsgDialogVisible = false;
                    this.getData();
                }
            })
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatGender: function (row, column, cellValue) {
            if (cellValue == '0') {
                return "未知";
            } else if (cellValue == '1') {
                return "男性";
            } else if (cellValue == '2') {
                return "女性";
            } else {
                return "未知";
            }
        },
        formatStatus: function (row, column, cellValue) {
            if (cellValue == '1') {
                return "已激活";
            } else if (cellValue == '2') {
                return "已禁用";
            } else if (cellValue == '4') {
                return "未激活";
            } else if (cellValue == '5') {
                return "退出企业";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#employeeTable', '数据.xlsx');
        },
        add: function () {
            addWorkEmployee(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateWorkEmployee(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        sync: function () {
            if (!this.condition.search.workCorpId) {
                this.$message({
                    type: 'error',
                    message: '请先选择企业!'
                });
                return;
            }
            this.$confirm('请确认是否同步, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                syncWorkEmployee({workCorpId: this.condition.search.workCorpId}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '同步成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onRefresh: function (row) {
            this.$confirm('请确认是否刷新, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                refreshWorkEmployee({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '刷新成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteWorkEmployee({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取公司列表
        getCorps: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getWorkCorpByPage(condition).then(data => {
                this.corps = data.body.rows;
            });
        },
        // 获取表格数据
        getData: function () {
            if (this.workCorpId) {
                this.condition.search.workCorpId = this.workCorpId;
            }
            getWorkEmployeeByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.setChecked();
            });
            this.getCorps();
        },
        // 设置多选
        setChecked: function () {
            this.$refs.employeeTable.clearSelection();
            this.selected.forEach(item => {
                this.$nextTick(() => {
                    this.tableData.find(obj => {
                        if (item.id === obj.id) {
                            this.$refs.employeeTable.toggleRowSelection(obj, true)
                        }
                    })
                })
            })
        }
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
